package com.sky.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.constant.StatusConstant;
import com.sky.dto.DishDTO;
import com.sky.dto.DishPageQueryDTO;
import com.sky.entity.Dish;
import com.sky.entity.DishFlavor;
import com.sky.entity.Setmeal;
import com.sky.exception.DeletionNotAllowedException;
import com.sky.mapper.DishFlavorMapper;
import com.sky.mapper.DishMapper;
import com.sky.mapper.SetmealDishMapper;
import com.sky.mapper.SetmealMapper;
import com.sky.result.PageResult;
import com.sky.service.DishService;
import com.sky.vo.DishVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

@Service
@Slf4j
public class DishServiceImpl implements DishService {
    @Autowired
    private DishMapper dishMapper;
    @Autowired
    private DishFlavorMapper dishFlavorMapper;
    @Autowired
    private SetmealDishMapper setmealDishMapper;
    @Autowired
    private SetmealMapper setmealMapper;

    /**
     * 新增菜品和对应的口味
     *
     * @param dishDTO 1
     */
    @Transactional
    /*@Transactional作用:将当前方法交给spring进行事务管理，执行失败则回滚事务，
    在SkyApplication中@EnableTransactionManagement已开启注解方式的事务管理*/
    @Override
    public void saveWithFlavor(DishDTO dishDTO) {
        Dish dish = new Dish();
        BeanUtils.copyProperties(dishDTO, dish);
        //向菜品表插入1条数据
        dishMapper.insert(dish);
        //获取insert生成的主键值
        Long dishId = dish.getId();//原本为空，因为xml映射文件useGeneratedKeys="true" keyProperty="id"，所以能获取到id
        //向口味表插入N条数据
        List<DishFlavor> flavors = dishDTO.getFlavors();
        //因为flavors可选，因此需要先判断是否为空
        if (flavors != null && !flavors.isEmpty()) {
            //插入数据前遍历集合插入dishId
            flavors.forEach(myFlavor -> myFlavor.setDishId(dishId));
            dishFlavorMapper.insertBatch(flavors);
        }
    }

    /**
     * 菜品分页查询
     *
     * @param dishPageQueryDTO 1
     * @return 1
     */
    @Override
    public PageResult pageQuery(DishPageQueryDTO dishPageQueryDTO) {
        //基于PageHelper执行分页查询
        PageHelper.startPage(dishPageQueryDTO.getPage(), dishPageQueryDTO.getPageSize());
        Page<DishVO> page = dishMapper.pageQuery(dishPageQueryDTO);
        return new PageResult(page.getTotal(), page.getResult());
    }

    /**
     * 批量删除菜品
     *
     * @param ids 1
     */
    @Transactional
    @Override
    public void deleteByIds(List<Long> ids) {
        //判断能否删除——是否正在售卖
        for (Long id : ids) {
            Dish dish = dishMapper.getById(id);//获取当前id的菜品
            if (dish.getStatus() == StatusConstant.ENABLE) {//StatusConstant.ENABLE代替1
                //成立则表示当前菜品正在售卖，不能删除
                throw new DeletionNotAllowedException(MessageConstant.DISH_ON_SALE);
            }
        }
        //判断能否删除——是否与套餐关联
        List<Long> setMealIds = setmealDishMapper.getSetmealIdsByDishIds(ids);
        if (setMealIds != null && !setMealIds.isEmpty()) {
            //成立则表示当前菜品被套餐关联，不能删除
            throw new DeletionNotAllowedException(MessageConstant.DISH_BE_RELATED_BY_SETMEAL);
        }
        //删除菜品和相关口味
//        for (Long id : ids) {
//            dishMapper.deleteById(id);
//            //删除关联的口味数据
//            dishFlavorMapper.deleteByDishId(id);
//        }//老版每个id都要创建两个sql语句，效率低，
        dishMapper.deleteByIds(ids);
        dishFlavorMapper.deleteByIds(ids);
    }

    /**
     * 根据ID查询菜品及口味
     *
     * @param id 1
     * @return 1
     */
    @Override
    public DishVO getByIdWithFlavor(Long id) {
        //根据ID查询菜品数据
        Dish dish = dishMapper.getById(id);//之前已在dishMapper中编写了getById()方法
        //根据菜品ID查询口味数据
        List<DishFlavor> dishFlavors = dishFlavorMapper.getByDishId(id);
        //将查询到的数据封装进DishVO
        log.info(dishFlavors.toString());
        DishVO dishVO = new DishVO();
        BeanUtils.copyProperties(dish, dishVO);//将获取到的Dish拷贝到dishVO中
        dishVO.setFlavors(dishFlavors);
        return dishVO;
    }

    /**
     * 修改id对应的菜品和口味
     *
     * @param dishDTO 1
     */
    @Override
    public void upadateDishAndFlavor(DishDTO dishDTO) {
        Dish dish = new Dish();
        BeanUtils.copyProperties(dishDTO, dish);
        //修改菜品基本信息
        dishMapper.update(dish);
        //删除原有的口味数据
        dishFlavorMapper.deleteByDishId(dishDTO.getId());
        //添加新的口味数据
        List<DishFlavor> flavors = dishDTO.getFlavors();
        //因为flavors可选，因此需要先判断是否为空
        if (flavors != null && !flavors.isEmpty()) {
            //插入数据前遍历集合插入dishId
            flavors.forEach(myFlavor -> myFlavor.setDishId(dishDTO.getId()));
            dishFlavorMapper.insertBatch(flavors);
        }
    }

    /**
     * 菜品起售、停售
     *
     * @param status 1
     * @param id     1
     */
    @Transactional//因为涉及多张表所以需开启事务管理
    @Override
    public void updateStatus(Integer status, Long id) {
        Dish dish = Dish.builder()
                .status(status)
                .id(id)
                .build();
        dishMapper.update(dish);

        // 如果是停售操作，还需要将包含当前菜品的套餐也停售
        if (status == StatusConstant.DISABLE) {
            //getSetMealIdsByDishIds()方法要求传参List，构建List并将id传入
            List<Long> dishIds = new ArrayList<>();
            dishIds.add(id);
            // 查询包含当前菜品的多个套餐ID，并放入列表中
            List<Long> setMealIds = setmealDishMapper.getSetmealIdsByDishIds(dishIds);
            // 如果存在相关套餐，则进行停售处理
            if (setMealIds != null && setMealIds.size() > 0) {
                for (Long setmealId : setMealIds) {
                    // 构建Setmeal对象并设置状态和ID
                    Setmeal setmeal = Setmeal.builder()
                            .id(setmealId)
                            .status(StatusConstant.DISABLE)
                            .build();
                    // 更新套餐信息
                    setmealMapper.update(setmeal);
                }
            }
        }
    }

    /**
     * 根据分类id查询菜品
     * @param categoryId
     * @return
     */
    @Override
    public List<Dish> list(Long categoryId) {
        Dish dish = Dish.builder()
                .categoryId(categoryId)
                .status(StatusConstant.ENABLE)
                .build();
        return dishMapper.list(dish);
    }

    /**
     * 条件查询菜品和口味
     * @param dish
     * @return
     */
    public List<DishVO> listWithFlavor(Dish dish) {
        List<Dish> dishList = dishMapper.list(dish);

        List<DishVO> dishVOList = new ArrayList<>();

        for (Dish d : dishList) {
            DishVO dishVO = new DishVO();
            BeanUtils.copyProperties(d,dishVO);

            //根据菜品id查询对应的口味
            List<DishFlavor> flavors = dishFlavorMapper.getByDishId(d.getId());

            dishVO.setFlavors(flavors);
            dishVOList.add(dishVO);
        }
        return dishVOList;
    }
}













